package wykop.parser;

import org.apache.log4j.Logger;

import wykop.page.WykopComment;
import wykop.page.WykopUser;
import wykop.utils.Convert;
import wykop.utils.XPathUtils;

import com.google.common.base.Preconditions;

/**
 * Created by IntelliJ IDEA. User: kad Date: 05.11.11 Time: 13:23 To change this
 * template use File | Settings | File Templates.
 */
public class WykopCommentParser {

	private final static Logger logger = Logger
			.getLogger("wykop.parsing.comment");

	private static WykopComment fromNode(final org.w3c.dom.Node node,
			final UserProvider userProvider) throws NoCommentParsed {
		Preconditions.checkNotNull(node);
		Preconditions.checkNotNull(userProvider);

		try {
			final String text = XPathUtils.extractString(node,
					".//blockquote/p").trim();
			final WykopUser user = userProvider.getUserForName(XPathUtils
					.extractString(node, ".//blockquote/header/a").trim());
			final int points = parse(XPathUtils.extractString(node,
					".//blockquote/header/span/strong/span").trim());

			final WykopComment comment = new WykopComment();// </editor-fold>
			comment.setAuthor(user);
			comment.setScore(points);
			comment.setText(text);

			return comment;
		} catch (final Exception e) {
			logger.warn("Failed to parse comment, because of: "
					+ e.getLocalizedMessage());
			throw new NoCommentParsed(e);
		}

	}

	public static ICommentParser getCommentParser(
			final UserProvider userProvider) {
		return new ICommentParser() {
			@Override
			public WykopComment parseComment(final org.w3c.dom.Node node)
					throws NoCommentParsed {
				return fromNode(node, userProvider);
			}
		};
	}

	private static int parse(final String s) {
		if (s.startsWith("+")) {
			return Convert.toInt(s.substring(1));
		} else {
			return Convert.toInt(s);
		}
	}

}
